package com.quan.upms.web.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.IdWorker;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.quan.common.base.annotation.Log;
import com.quan.common.base.bean.PageBean;
import com.quan.common.base.bean.ResponseMsg;
import com.quan.common.base.bean.ResultBean;
import com.quan.common.base.constant.CommonConstant;
import com.quan.common.core.support.BaseController;
import com.quan.common.utils.PasswordUtils;
import com.quan.common.utils.RandomUitl;
import com.quan.sdk.oss.qiniu.QiniuOSSUtils;
import com.quan.upms.dto.UpmsUserDto;
import com.quan.upms.entity.UpmsUser;
import com.quan.upms.service.UpmsUserService;

/**
 * <p>
 * 通用用户权限系统-用户表 前端控制器
 * </p>
 *
 * @author 杨浩泉
 * @since 2018-05-13
 */
@RestController
@RequestMapping("/upms/user")
public class UpmsUserController extends BaseController {

	@Autowired
	private UpmsUserService service;

	@Autowired
	private IdWorker idWorker;

	@Autowired
	private AmqpTemplate amqpTemplate;

	@Autowired
	private QiniuOSSUtils qiniuOSSUtils;

	/**
	 * 添加
	 * 
	 * @param entity
	 *            实体
	 * @return ResultBean
	 */
	@Log
	@PostMapping("/add")
	public Object add(@Valid @RequestBody UpmsUser entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultBean.failure(bindingResult.getFieldError().getRejectedValue().toString());
		}

		entity.setId(idWorker.nextId());
		// 加密盐
		entity.setSalt(RandomUitl.uuid());
		// 生成密码
		String password = RandomUitl.generateInteger(6);
		entity.setPassword(PasswordUtils.encodePassword(password, entity.getSalt()));
		UpmsUser insertSelective = this.service.insertSelective(entity);
		if (null != insertSelective) {
			// 发送短信或邮件告知用户账号和密码
			entity.setPassword(password);
			this.amqpTemplate.convertAndSend(CommonConstant.EXCHANGE_TOPIC, CommonConstant.MQ_TOPIC_MESSAGE_MAIL, entity);

			return ResultBean.ok();
		} else {
			return ResultBean.failure();
		}
	}

	/**
	 * 批量删除
	 * 
	 * @param params
	 *            idList(JSON):["1","2"]
	 * @return ResultBean
	 */
	@Log
	@PostMapping("/delete")
	public Object delete(@RequestBody Map<String, Object> params) {
		if (null != params && !params.isEmpty()) {
			List<Long> idList = JSON.parseArray(params.get("idList").toString(), Long.class);
			int count = this.service.deleteByIds(StringUtils.join(idList, ","));
			if (count > 0) {
				return ResultBean.ok();
			} else {
				return ResultBean.failure("通过ID删除失败：[ " + idList + " ]");
			}
		}
		return ResultBean.failure("请选项需要删除的记录");
	}

	/**
	 * 修改
	 * 
	 * @param entity
	 *            实体
	 * @return ResultBean
	 */
	@Log
	@PostMapping("/update")
	public Object update(@Valid @RequestBody UpmsUser entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultBean.failure(bindingResult.getFieldError().getDefaultMessage().toString());
		}
		int count = this.service.updateSelective(entity);
		if (count > 0) {
			return ResultBean.ok();
		} else {
			return ResultBean.failure();
		}
	}

	/**
	 * 通过ID查询
	 * @param id
	 * @return
	 */
	@Log
	@GetMapping("/get/{id}")
	public Object get(@PathVariable Long id) {
		UpmsUser entity = this.service.selectOneById(id);
		if (null != entity) {
			return ResultBean.ok(entity);
		} else {
			return ResultBean.failure("通过ID查询失败：[ " + id + " ]");
		}
	}

	/**
	 * 多条件查询数据列表
	 *
	 * @param entiy
	 *            实体对象（查询条件）
	 * @return 分页对象
	 */
	@GetMapping(value = "/list")
	public Object list(UpmsUser entity) {
		return ResultBean.ok(this.service.selectAll(entity));
	}

	/**
	 * 多条件查询分页数据
	 *
	 * @param entiy
	 *            实体对象（查询条件）
	 * @return 分页对象
	 */
	@Log(desc="用户查询多条件查询分页数据")
	@GetMapping(value = "/page")
	public Object page(UpmsUser entity) {
		return ResultBean.ok(this.service.selectPage(entity, new PageBean(request)));
	}

	/**
	 * 根据账号查找用户
	 * 
	 * @param account
	 * @return
	 */
	@GetMapping(value = "/findByAccount/{account}")
	public ResultBean findByAccount(@PathVariable String account) {
		UpmsUser findByAccount = this.service.findByAccount(account);
		if (null != findByAccount) {
			return ResultBean.ok(findByAccount);
		} else {
			return ResultBean.failure("根据账号[" + account + "]查找用户信息失败");
		}
	}

	/**
	 * 查找用户角色
	 * 
	 * @param userId
	 * @return
	 */
	@GetMapping(value = "/findRolesByUserId/{userId}")
	public ResultBean findRolesByUserId(@PathVariable Long userId) {
		return ResultBean.ok(this.service.findRolesByUserId(userId));
	}

	/**
	 * 查找用户权限
	 * 
	 * @param userId
	 * @return
	 */
	@GetMapping(value = "/findPermissionsByUserId/{userId}")
	public ResultBean findPermissionsByUserId(@PathVariable Long userId) {
		return ResultBean.ok(this.service.findPermissionsByUserId(userId));
	}

	/**
	 * 修改个人登录密码
	 * 
	 * @param dto
	 * @return
	 */
	@PostMapping(value = "/updateMyPassword")
	public Object updateMyPassword(@RequestBody UpmsUserDto dto) {
		try {
			if (StringUtils.isBlank(dto.getOldPassword())) {
				return ResultBean.warning("原密码不能为空");
			}
			if (StringUtils.isBlank(dto.getNewPassword())) {
				return ResultBean.warning("新密码不能为空");
			}
			this.service.updatePassword(dto.getId(), dto.getOldPassword(), dto.getNewPassword());
			return ResultBean.ok();
		} catch (RuntimeException e) {
			return ResultBean.failure(e.getMessage());
		}
	}

	/**
	 * 修改个人基本信息
	 * 
	 * @param entity
	 * @return
	 */
	@PostMapping(value = "/updateMyInfo")
	public Object updateMyInfo(@RequestBody UpmsUser entity) {
		if (StringUtils.isBlank(entity.getRealName())) {
			return ResultBean.warning("姓名不能为空");
		}
		if (StringUtils.isBlank(entity.getEmail())) {
			return ResultBean.warning("邮件地址不能为空");
		}
		if (StringUtils.isBlank(entity.getMobile())) {
			return ResultBean.warning("手机号码不能为空");
		}

		UpmsUser oldUser = this.service.selectOneById(entity.getId());
		if (null != oldUser.getRealName() && !oldUser.getRealName().equals(entity.getRealName())) {
			if (this.service.existValue(UpmsUser.class, "realName", entity.getRealName()) > 0) {
				return ResultBean.failure("名称已存在");
			}
		}
		if (null != oldUser.getEmail() && !oldUser.getEmail().equals(entity.getEmail())) {
			if (this.service.existValue(UpmsUser.class, "email", entity.getEmail()) > 0) {
				return ResultBean.failure("编码已存在");
			}
		}
		if (null != oldUser.getMobile() && !oldUser.getMobile().equals(entity.getMobile())) {
			if (this.service.existValue(UpmsUser.class, "mobile", entity.getMobile()) > 0) {
				return ResultBean.failure("编码已存在");
			}
		}
		this.service.updateSelective(entity);

		return ResultBean.ok();
	}
	
	/**
	 * 上传头像
	 * @param request
	 * @param ossName
	 * @param bucketName
	 * @param prefixName
	 * @return
	 */
	@PostMapping(value = "/uploadAvatar")
	public Object uploadAvatar(HttpServletRequest request, String ossName, String bucketName, String prefixName) {
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

			// 取得MultiValueMap集合
			MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();
			Set<Entry<String, List<MultipartFile>>> entrySet = multiFileMap.entrySet();
			for (Entry<String, List<MultipartFile>> entry : entrySet) {

				// 获取MultipartFile集合
				List<MultipartFile> multipartFiles = entry.getValue();
				for (MultipartFile multipartFile : multipartFiles) {
					ResponseMsg upload = this.qiniuOSSUtils.upload(bucketName, multipartFile.getBytes(), multipartFile.getOriginalFilename(), prefixName) ;
					return ResultBean.ok(upload);
				}
			}
		} catch (IOException e) {
			return ResultBean.errorMsg("文件上传失败") ;
		}
		return ResultBean.ok();
	}
}
